import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
// import "@/components/NProgress/nprogress.less"; // progress bar custom style
// import { setDocumentTitle, domTitle } from "@/utils/domUtil";

const loginRoutePath = "/user/login";
const defaultRoutePath = "/";
const allowList = ["login", "register", "registerResult"]; // 白名单页面

router.beforeEach((to, from, next) => {
  /**
   * 如果有token
   * 1.判断去的页面是否为登陆页面，如果为登录页则返回默认页面
   * 2.如果不为登陆页面则放行
   * 如果没有token
   * 1.如果在白名单中则放行
   * 2.如果不在白名单则跳到登陆页面
   */
  NProgress.start();
  const hasToken = store.getters.authInfo.token;
  if (hasToken) {
    if (to.path === loginRoutePath) {
      next({
        path: defaultRoutePath
      });
    } else {
      if (store.getters.assets.roles && store.getters.assets.roles.length) {
        next();
      } else {
        store.dispatch("getMenus").then(res => {
          const redirect = decodeURIComponent(from.query.redirect || to.path)
          if (to.path === redirect) {
            // set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true })
          } else {
            // 跳转到目的路由
            next({ path: redirect })
          }
        });
      }
    }
    NProgress.done();
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next();
    } else {
      next({
        path: loginRoutePath,
        query: {
          redirect: to.fullPath
        }
      });
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});
